package com.kll.tv.utils

import android.content.Context
import android.os.Handler
import android.os.Message
import com.blankj.utilcode.util.ToastUtils
import com.kll.carolinehmibiz.AccountManager
import com.kll.carolinehmibiz.OperationManager
import com.kll.carolinehmibiz.model.OperateListener
import com.kll.carolinehmibiz.base.utils.L
import com.tencent.imsdk.v2.V2TIMCallback
import com.tencent.imsdk.v2.V2TIMSDKListener
import com.tencent.qcloud.tuicore.TUILogin


/**
 * ====================================================
 * Created by Ziliang Cai on 2021/12/25 8:23 下午
 * <a href="mailto:752777456@qq.com">Contact me</a>
 * ====================================================
 */
class TUICallingService(context: Context) {

    private var mContext = context.applicationContext
    private var mInitState = false
    private var mLoginState = false
    private var mSyncSigIsBusying = false
    private var mIsBusying = false
    private var syncSigFailedAccount =  1L

    //
    private val WHAT_LOGIN = 1
    private val WHAT_SYNC_SIG = 2

    companion object {

        private var mInstance: TUICallingService? = null

        fun getInstance(context: Context): TUICallingService {

            if(mInstance == null) {
                mInstance = TUICallingService(context)
            }

            return mInstance!!
        }
    }

    /**
     * 同步配置
     */
    private fun syncSig(){

        if(mSyncSigIsBusying) return
        mSyncSigIsBusying = true

        L.e(">>>", "TUICallingService>>syncSig")
        OperationManager.getInstancce().getUserSig(object: OperateListener {
            override fun onSuccess(state: Int, obj: Any?) {
                if(obj != null) {
                    // 同步配置完成，
                    mHandler.sendEmptyMessage(WHAT_LOGIN)
                    syncSigFailedAccount = 1
                    mSyncSigIsBusying = false
                }

                L.e(">>>", "TUICallingService>>syncSig>>onSuccess:: obj is ${if(obj == null) "null" else "not null"}")
            }

            override fun onFail(code: Int, message: String) {
                // 配置生成失败了，10s后重新尝试
                mHandler.sendEmptyMessageDelayed(WHAT_SYNC_SIG, 5000 * syncSigFailedAccount)
                syncSigFailedAccount++
                mSyncSigIsBusying = false

                L.e(">>>", "TUICallingService>>syncSig>>onFail:: code = ${code}")
            }
        })
    }
    /**
     * Handler
     */
    private var mHandler = object: Handler(mContext.mainLooper) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)

            when(msg.what) {
                WHAT_LOGIN->{
                    init()
                    login()
                }
                WHAT_SYNC_SIG->{
                    syncSig()
                }
            }
        }
    }

    fun init(){

        var appId = AccountManager.getInstancce().getSdkAppId()


        L.e(">>>", "TUICallingService>>init:: appId = ${appId}, mInitState = $mInitState")
        if(appId == null){
            syncSig()
            return
        }

        if(!mInitState) {

            mInitState = true

            TUILogin.init(mContext!!, appId.toInt(), null, object : V2TIMSDKListener() {
                override fun onKickedOffline() {
                    super.onKickedOffline()

                    // 当前处于离线状态
                    mLoginState = false
                    L.e(">>>", "TUICallingService>>syncSig>>init>>onKickedOffline")
                }

                override fun onUserSigExpired() {
                    super.onUserSigExpired()

                    // 签名过期，重新生成加密串
                    syncSig()

                    L.e(">>>", "TUICallingService>>syncSig>>init>>onUserSigExpired")
                }
            })

            login()
        }
    }

    /**
     * 登录
     */
    fun login(){

        var userInfo = AccountManager.getInstancce().getLoginUserInfo()
        var userSig = AccountManager.getInstancce().getUserSig()
//        var userSig = AccountModel.getInstance(mContext).getUserSig()

        L.e(">>>", "TUICallingService>>syncSig>>login:: userId = ${userInfo?.tencent_user_id}, userSig = ${userSig}, mLoginState =  ${mLoginState}, mIsBusying = ${mIsBusying}")
        // 如果还未获取到用户加密串，则去同步
        if(userSig == null) {
            syncSig()
            return
        }

        if(userInfo != null && mInitState && !mLoginState && !mIsBusying) {

            mIsBusying = true
            TUILogin.login(userInfo.tencent_user_id, userSig, object : V2TIMCallback {
                override fun onSuccess() {
                    ToastUtils.showLong("登录成功！")
                    mLoginState = true
                    mIsBusying = false
                    L.e(">>>", "TUICallingService>>syncSig>>login>>onSuccess")
                }

                override fun onError(p0: Int, p1: String?) {
//                binding.tvStatus.text = "p0:${p0}, p1:${p1}"
                    mLoginState = false
                    mIsBusying = false

                    mHandler.sendEmptyMessageDelayed(WHAT_SYNC_SIG, 5000 * syncSigFailedAccount)
                    L.e(">>>", "TUICallingService>>syncSig>>login>>onError:: p0 = ${p0}, p1 = ${p1}")
                }
            })
        } else if(mIsBusying){
            // 如果用户调用了login，但此时处于忙碌状态，则3秒后重试(因为有可能是快速切换账号)
            mHandler.removeMessages(WHAT_LOGIN)
            mHandler.sendEmptyMessageDelayed(WHAT_LOGIN, 5000)
        }
    }

    /**
     * 是否登录
     */
    fun isLogin(): Boolean {
        return mLoginState
    }
}